<template>
  <div class="container">
    <div class="top">
      <el-form :model="form" label-width="120px" :inline="true">
        <el-row>
          <el-col :span="5">
            <el-form-item label="识别方式">
              <el-select v-model="form.action">
                <el-option :label="item.label" :value="item.id" v-for="(item,key) in actionList" :key="key"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-upload
                  class="upload-demo"
                  action=""
                  multiple
                  accept="image/*"
                  name="file"
                  :on-change="changeFile"
                  :show-file-list="false"
                  :limit="20"
                  :disabled="false"
                  :auto-upload="false"
                  :on-success="uploadSuccess"
              >
                <el-button type="primary">选择文件</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :disabled="upload_btn" @click="onSubmit">上传识别</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提取字符">
              <el-select v-model="form.tiqu" clearable allow-create filterable>
                <el-option :label="item.label" :value="item.id" v-for="(item,key) in tiqu_list" :key="key"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button :disabled="tiqu_btn" type="success" @click="tiquText">提取</el-button>
            </el-form-item>
          </el-col>

          <el-col :span="1">
            <el-form-item>
              <el-button @click="refresh">刷新</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </div>
    <div class="center">
      <div class="left">
        <template v-if="res_data.length>0">
          <el-row style="width: 100%; margin-bottom: 10px;" v-for="(item,key) in res_data" :key="key">
            <el-col :span="24" style="margin-right: 20px;">
              <el-card :body-style="{ padding: '0px' }">
                <div style="padding: 14px">
                  <span class="content text-ellipsis">{{ item.content }}</span>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </template>

      </div>

      <div class="right">
        <template v-if="copy_data.length>0">
          <el-card :body-style="{ padding: '0px' }">
            <div style="padding: 14px">
              <span class="content text-ellipsis" v-for="(item,index) in copy_data" :key="index">
                {{ item }}
              </span>
            </div>
          </el-card>
          <el-button @click="copyBtn">复制</el-button>
        </template>

      </div>
    </div>
  </div>


</template>
<script setup>
import {reactive, ref, watch} from 'vue'
import {ElNotification} from 'element-plus'

/**
 * 将中文符号转换成英文符号
 */
function chineseChar2englishChar(chineseChar) {
  // 将单引号‘’都转换成'，将双引号“”都转换成"
  let str = chineseChar.replace(/[’|‘]/g, "'").replace(/[“|”]/g, "\"");
  // 将中括号【】转换成[]，将大括号｛｝转换成{}
  str = str.replace(/【/g, "[").replace(/】/g, "]").replace(/｛/g, "{").replace(/｝/g, "}");
  // 将逗号，转换成,，将：转换成:
  str = str.replace(/，/g, ",").replace(/：/g, ":");
  //将《转换为<，将》转换为>
  str = str.replace(/《/g, "<").replace(/》/g, ">");
  //将句号。转换成.，将问号？转换为?
  str = str.replace(/。/g, ".").replace(/？/g, "?");
  //将！转换为!
  str = str.replace(/！/g, "!");
  str = str.replace(/\s/g, "");
  return str;
}

const actionList = [
  {
    id: "RecognizeAdvanced",
    label: "高精识别",
  },
  {
    id: "RecognizeHandwriting",
    label: "手写",
  },
  {
    id: "RecognizeBasic",
    label: "电商文字",
  },
  {
    id: "RecognizeGeneral",
    label: "通用文字",
  },
  {
    id: "RecognizeTableOcr",
    label: "表格",
  }
];
const tiqu_list = [
  {
    id: "子订单编号:",
    value: "子订单编号:"
  },
  {
    id: "父订单编号:",
    value: "父订单编号:"
  },
  {
    id: "订单编号:",
    value: "订单编号:"
  },
  {
    id: "账单编号:",
    value: "账单编号:"
  },
  {
    id: "订单号:",
    value: "订单号:"
  },
  {
    id: "发票号码:",
    value: "发票号码:"
  },
];
const upload_btn = ref(true);
const tiqu_btn = ref(true);
let res_data = ref([]);
let copy_data = reactive([]);
const form = reactive({
  tiqu: '',
  action: 'RecognizeAdvanced',
  file: [],
})
const onSubmit = async () => {
  let formdata = new FormData();
  form.file.forEach(item => {
    formdata.append('files', item)
  });
  formdata.set('action', form.action)
  let m = await fetch("/upload", {
    method: "POST",
    body: formdata,
  }).then(res => res.json()).then(value => value)
  res_data.value = m.map(item => {
    return {content: chineseChar2englishChar(item.content)}
  });
}
watch(() => form.file, (value) => {
  upload_btn.value = value.length <= 0;
}, {
  immediate: true,
  deep: true
});

watch([res_data, () => form.tiqu], ([res, tiqu], [prevName, prevAge]) => {
  tiqu_btn.value = !(res.length > 0 && tiqu !== "");
})

const uploadSuccess = (res) => {
  console.log(res)
}
const changeFile = (file) => {
  form.file.push(file.raw)
}
const tiquText = () => {
  if (!form.tiqu) {
    return;
  }

  if (res_data.value.length === 0) {
    return;
  }
  copy_data=[];
  const reg = new RegExp(`${form.tiqu}\\d+(\\.[0-9]{1,2})?`, 'g');
  res_data.value.forEach(res => {
    let arr = res.content.match(reg);
    if (arr) {
      let copy = arr.map(item => item.slice(form.tiqu.length));
      copy_data.push(...copy)
    }
  })
}
const copyBtn = () => {
  navigator.clipboard.writeText(copy_data.join('\n')).then(
      () => {
        ElNotification({
          title: '提示',
          message: '粘贴文本成功',
          type: 'success',
        })
      },
      () => {
        ElNotification({
          title: '警告',
          message: '浏览器不支持,请手动复制!',
          type: 'error',

        })
      }
  );
}
const refresh = () => {
  // form.tiqu='';
  form.file = [];
  res_data.value = [];
  copy_data = [];
}
</script>
<style lang="scss">
.container {
  .top {
    width: 90%;
  }

  .center {
    display: flex;
    flex-wrap: wrap;

    .left {
      width: 70%;
      margin-right: 10px;
    }

    .right {
      width: 28%;
    }
  }

  .content {
    width: 100%;
  }

  .text-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 3;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }
}
</style>
